import React, { useState } from "react";
import {
  Form,
  Input,
  Button,
  Card,
  Layout,
  Checkbox,
  message,
  Divider,
  Space,
} from "antd";
import {
  UserOutlined,
  LockOutlined,
  WechatOutlined,
  AlipayCircleOutlined,
} from "@ant-design/icons";
import { useNavigate } from "react-router-dom";
import styles from "./index.module.less";
import type { LoginFormData, SocialLoginType } from "./types";
import { authService } from "../../services/auth";
import { setSession } from "../../utils/storage";

/**
 * @description 登录页面组件
 * @returns {JSX.Element} 登录页面
 */
const LoginPage: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [socialLoading, setSocialLoading] = useState<SocialLoginType | null>(
    null
  );
  const navigate = useNavigate();
  const [form] = Form.useForm();

  /**
   * @description 处理登录请求
   * @param data 登录表单数据
   */
  const handleLogin = async (data: LoginFormData) => {
    const params = {
      phone: data.phone,
      password: data.password,
    };
    const res = await authService.login(params);
    if (res.code === 0) {
      setSession("token", res.result.token);
      setSession("userInfo", res.result);
      navigate("/dashboard");
    }
  };

  /**
   * @description 处理社交媒体登录
   * @param type 社交媒体类型
   */
  const handleSocialLogin = async (type: SocialLoginType) => {
    try {
      setSocialLoading(type);
      const url = authService.getSocialLoginUrl(type);
      window.location.href = url;
    } catch (error) {
      message.error(
        error instanceof Error ? error.message : "登录失败，请重试"
      );
      setSocialLoading(null);
    }
  };

  /**
   * @description 处理表单提交
   * @param values 表单值
   */
  const onFinish = async (values: LoginFormData) => {
    setLoading(true);
    try {
      await handleLogin(values);
    } finally {
      setLoading(false);
    }
  };

  // 获取保存的用户名
  // React.useEffect(() => {
  //   const savedUsername = localStorage.getItem("username");
  //   if (savedUsername) {
  //     form.setFieldsValue({ username: savedUsername, remember: true });
  //   }
  // }, [form]);

  return (
    <Layout className={styles.loginContainer}>
      <div className={styles.geometricShapes} />
      <div className={styles.loginWrapper}>
        <div className={styles.leftSection}>
          <img
            src="/images/login-illustration.svg"
            alt="AI金融助手"
            className={styles.illustration}
          />
        </div>
        <Card className={styles.loginCard}>
          <h1 className={styles.title}>AI金融助手</h1>
          <p className={styles.subtitle}>您的智能金融顾问</p>
          <Form
            form={form}
            name="login"
            onFinish={onFinish}
            size="large"
            className={styles.loginForm}
            initialValues={{ remember: false }}
          >
            <Form.Item
              name="phone"
              rules={[{ required: true, message: "请输入手机号" }]}
            >
              <Input prefix={<UserOutlined />} placeholder="请输入手机号" />
            </Form.Item>
            <Form.Item
              name="password"
              rules={[
                { required: true, message: "请输入密码" },
                { min: 6, message: "密码长度不能小于6位" },
              ]}
            >
              <Input.Password prefix={<LockOutlined />} placeholder="密码" />
            </Form.Item>
            <Form.Item>
              <Form.Item name="remember" valuePropName="checked" noStyle>
                <Checkbox>记住用户名</Checkbox>
              </Form.Item>
            </Form.Item>
            <Form.Item>
              <Button type="primary" htmlType="submit" block loading={loading}>
                登录
              </Button>
            </Form.Item>
            {/* 
            <Divider>其他登录方式</Divider>

            <div className={styles.socialLogin}>
              <Space size="large">
                <Button
                  icon={<WechatOutlined />}
                  onClick={() => handleSocialLogin("wechat")}
                  loading={socialLoading === "wechat"}
                  className={styles.wechatBtn}
                >
                  微信登录
                </Button>
                <Button
                  icon={<AlipayCircleOutlined />}
                  onClick={() => handleSocialLogin("alipay")}
                  loading={socialLoading === "alipay"}
                  className={styles.alipayBtn}
                >
                  支付宝登录
                </Button>
              </Space>
            </div> */}
          </Form>
        </Card>
      </div>
    </Layout>
  );
};

export default LoginPage;
